package com.yonyou.jrmob.contacts.schedule.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.yonyou.jrmob.contacts.R;
import com.yonyou.jrmob.contacts.schedule.adapter.ScheduleAdapter;
import com.yonyou.jrmob.contacts.schedule.view.date.CalendarCard;
import com.yonyou.jrmob.contacts.schedule.view.date.CalendarViewAdapter;
import com.yonyou.jrmob.contacts.schedule.view.date.CustomDate;
import com.yonyou.jrmob.contacts.schedule.vo.ScheduleDetail;
import com.yonyou.uap.um.service.ServiceCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jrmob.yonyou.com.commonlib.app_config_tool.constant.Constant;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.CommonUtil;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.LogUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.MobUtils;
import jrmob.yonyou.com.commonlib.app_config_tool.tool.base.StatusBarUtil;
import jrmob.yonyou.com.commonlib.baseui.base.BaseActivityMob_lib;
import jrmob.yonyou.com.commonlib.login.bean.MAServices_lib;

public class ScheduleActivity extends BaseActivityMob_lib {

    private ImageView top_left;
    private ImageView top_right;
    private ImageView top_back;
    private Button btn_close;
    private ListView lv_detail;
    private TextView tv_title; // title
    private List<ScheduleDetail> scheduleList;
    private List<ScheduleDetail> scheduleListDay;
    private ScheduleAdapter adapter;
    private LinearLayout schedule_rili;
    private PopCalendar mCalendar;// 日历
    private int popheight;
    private List<String> haveScheduleList;
    private String dateString;
    private CustomDate setDate ;
    private CalendarCard calendarCard;
    private String clickDate;
    private CustomDate clickDateShare;//保存点击日期
    private Dialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        initActionbar();
        setContentView(R.layout.scheduledetail);
        initView(); // 初始化控件
        initListener(); // 添加监听
//        StatusBarUtil.StatusBarLightMode(this);
    }

    @Override
    public void initView() {
        loadingDialog = MobUtils.createLoadingDialog(this, "加载中请稍后...");
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("工作日历");
        lv_detail = (ListView) findViewById(R.id.lv_detail);
        schedule_rili = (LinearLayout) findViewById(R.id.rrrrr);
        top_left = (ImageView) findViewById(R.id.top_left);
        top_left.setVisibility(View.VISIBLE);
        top_left.setImageResource(R.mipmap.qiehuanrili);
        top_right = (ImageView) findViewById(R.id.top_right);
        top_right.setVisibility(View.VISIBLE);
        top_right.setImageResource(R.drawable.button_press_or);
        top_back = (ImageView) findViewById(R.id.top_back);
    }

    public void initListener(){
        top_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mCalendar != null && mCalendar.isShowing()){
                    top_left.setImageResource(R.mipmap.qiehuanrili);
                }else{
                    top_left.setImageResource(R.mipmap.qiehuanyueli);
                }
                isShowPop();
            }
        });
        top_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent22 = new Intent(ScheduleActivity.this, ScheduleMainActivity.class);
                intent22.putExtra("clickDate",clickDate);
                startActivityForResult(intent22, 22);
            }
        });
        top_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                closePop();
                finish();
            }
        });
        lv_detail.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                Intent intent = new Intent(ScheduleActivity.this,
                        ScheduleDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("detail", adapter.getItem(arg2));
                intent.putExtras(bundle);
                startActivityForResult(intent, 44);
            }
        });
    }
    public void initData(){

        if(null != clickDateShare){
            //clickDateSchedule(clickDateShare);
        }else{
            String date;
            if (null != setDate){
                date = setDate.getYear()+"-"+String.format("%02d",setDate.getMonth());
            }else{
                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM");
                date  = sdf.format(new Date());
            }

            callService(date,0,null,false,"0");
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (22 == requestCode && 33 == resultCode && clickDateShare!=null) {
            String year_month = clickDateShare.getYear()+"-"+String.format("%02d",clickDateShare.getMonth());
            callService(year_month,0,null,false,"2");

        }if (44 == requestCode && 55 == resultCode && clickDateShare!=null) {
            String year_month = clickDateShare.getYear()+"-"+String.format("%02d",clickDateShare.getMonth());
            callService(year_month,0,null,false,"2");

        }


    }

    /***
     * 调用后台服务
     * // date,
     // 0,
     // null,
     // false, 左右滑动标示
     // flag 0:初始化，1：左右滑动，2添加或删除后返回，3：点击当前月
     */
    public void callService(String date, final int position, final CalendarViewAdapter<CalendarCard> popAdapter, final boolean isRight, final String flag) {


        JSONObject json = new JSONObject();
        try {
            json.put("transtype", Constant.TRANSTYPE_QUERY_CALENDAR);
            json.put("user_id", getUserInfoLRY().getUser_id());
            json.put("uuidToken", Constant.TOKEN);
            json.put("date", date);
            if (!CommonUtil.isNetworkConnected(this)) {
                CommonUtil.showToast(this, "当前网络不可用,请检查!");
                return;
            }
            if (null != loadingDialog && !loadingDialog.isShowing()) {
                loadingDialog.show();
            }
            MAServices_lib.callMACommonService(this, new ServiceCallback() {
                @Override
                public void execute(JSONObject json) {
                    LogUtils.e("日程数据："+json.toString());
                    JSONObject jsObject;
                    JSONArray jsArray_o;
                    JSONArray jsArray_p;
                    //calendarlist_o ; calendarlist_p
                    try {
                        jsObject = (JSONObject) json.opt("result");
                        Object obj = jsObject.opt("retfkag");
                        // 有错误的时候
                        if (null != obj && obj.toString().trim().equals("1")) {
                            String msg = jsObject.optString("msg").toString().trim();
                            showMessage(msg);
                            if (msg.contains("请重新登录")) {
                                turnToLoginActivity(ScheduleActivity.this);
                            }
                            return;
                        }
                        jsArray_o = (JSONArray) jsObject.get("calendarlist_o");
                        jsArray_p = (JSONArray) jsObject.get("calendarlist_p");
                        scheduleList = new ArrayList<ScheduleDetail>();
                        haveScheduleList = new ArrayList<String>();
                        scheduleListDay = new ArrayList<ScheduleDetail>();

                        for (int i = 0; i < jsArray_o.length(); i++) {
                            ScheduleDetail Schedules = new ScheduleDetail();
                            Schedules.setType("A");
                            Schedules.setPk(jsArray_o.getJSONObject(i).getString("pk_calendar"));
                            Schedules.setTheme(jsArray_o.getJSONObject(i).getString("theme"));
                            Schedules.setStartTime(jsArray_o.getJSONObject(i).getString("beginTime"));
                            Schedules.setEndTime(jsArray_o.getJSONObject(i).getString("endTime"));
                            Schedules.setIsZhongYao(jsArray_o.getJSONObject(i).getString("isImportant"));
                            Schedules.setTiXing(jsArray_o.getJSONObject(i).getString("callTime"));
                            Schedules.setHuiYiShi(jsArray_o.getJSONObject(i).getString("roomNum"));
                            Schedules.setLocation(jsArray_o.getJSONObject(i).getString("place"));
                            Schedules.setMemo(jsArray_o.getJSONObject(i).getString("remark"));
                            Schedules.setStartPerson(jsArray_o.getJSONObject(i).getString("user_name"));
                            Schedules.setCanYuPerson(jsArray_o.getJSONObject(i).getString("participants"));

                            haveScheduleList.add(jsArray_o.getJSONObject(i).getString("beginTime"));
                            scheduleList.add(Schedules);
                            scheduleListDay.add(Schedules);

                        }
                        for (int i = 0; i < jsArray_p.length(); i++) {
                            ScheduleDetail Schedules = new ScheduleDetail();
                            Schedules.setType("B");
                            Schedules.setPk(jsArray_p.getJSONObject(i).getString("pk_calendar"));
                            Schedules.setTheme(jsArray_p.getJSONObject(i).getString("theme"));
                            Schedules.setStartTime(jsArray_p.getJSONObject(i).getString("beginTime"));
                            Schedules.setEndTime(jsArray_p.getJSONObject(i).getString("endTime"));
                            Schedules.setIsZhongYao(jsArray_p.getJSONObject(i).getString("isImportant"));
                            Schedules.setTiXing(jsArray_p.getJSONObject(i).getString("callTime"));
                            Schedules.setHuiYiShi(jsArray_p.getJSONObject(i).getString("roomNum"));
                            Schedules.setLocation(jsArray_p.getJSONObject(i).getString("place"));
                            Schedules.setMemo(jsArray_p.getJSONObject(i).getString("remark"));
                            Schedules.setStartPerson(jsArray_p.getJSONObject(i).getString("user_name"));
                            Schedules.setCanYuPerson(jsArray_p.getJSONObject(i).getString("participants"));

                            haveScheduleList.add(jsArray_p.getJSONObject(i).getString("beginTime"));
                            scheduleList.add(Schedules);
                            scheduleListDay.add(Schedules);
                        }

                        LogUtils.e("data = " + scheduleList.toString() + " ===== " + scheduleListDay.toString());
                        if (flag.equals("0")){

                            adapter = new ScheduleAdapter(ScheduleActivity.this,scheduleListDay);
                            lv_detail.setAdapter(adapter);
                        }else if(flag.equals("1")){

                            slide(popAdapter,isRight,position);
                            adapter.updataList(scheduleListDay);
                        }else if(flag.equals("2")){

                            calendarCard.initDate(haveScheduleList);
                            clickDateSchedule(clickDateShare);
                        }else{
                            calendarCard.centerSlide(haveScheduleList);
                            calendarCard.invalidate();
                            adapter.updataList(scheduleListDay);
                        }

                        if (loadingDialog != null && loadingDialog.isShowing()) {
                            loadingDialog.dismiss();
                        }
                        top_left.performClick();
                    } catch (JSONException e1) {
                        LogUtils.e(e1);
                        e1.printStackTrace();
                    }
                }
                @Override
                public void error(String arg0, String arg1) {
                    // 设置登录按钮可用性(登录请求后台有反应后可用)
                    if (loadingDialog != null && loadingDialog.isShowing()) {
                        loadingDialog.dismiss();
                    }
                    Toast.makeText(ScheduleActivity.this, arg0 + arg1,
                            Toast.LENGTH_LONG).show();
                    adapter = new ScheduleAdapter(ScheduleActivity.this, new ArrayList<ScheduleDetail>());
                    lv_detail.setAdapter(adapter);
                }
            }, json);


        } catch (Exception e) {
            // 设置登录按钮可用性(登录请求后台有反应后可用)
            Log.e("mmmm", e + "");
            e.printStackTrace();
        }
    }


    private PopCalendar getPopCalendar() {

        return new PopCalendar(this).getInstance(this, tv_title,
                Gravity.BOTTOM, new CalendarCard.OnCellClickListener() {

                    @Override
                    public void clickDate(CustomDate date) {
                        clickDateShare = date;
                        try {
                            SimpleDateFormat currSdf=new SimpleDateFormat("yyyy-MM-dd HH:mm");
                            String currDate=currSdf.format(new Date());
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                            clickDate  = sdf.format(sdf.parse(date.toString()))+" "+currDate.split(" ")[1];
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        clickDateSchedule(date);
                    }
                    @Override
                    public void changeDate(CustomDate date) {

                    }
                },haveScheduleList);
    }


    public void clickDateSchedule(CustomDate date){
        //数字的格式转换
        String date_day = String.format("%02d",date.getDay());
        if (null != scheduleListDay){
            scheduleListDay.clear();
        }
        if (scheduleList==null){
            return;
        }
        for (int i = 0;i<scheduleList.size();i++){
            String StartTimeString = scheduleList.get(i).getStartTime().toString();
            String[] StartTime = StartTimeString.replace(" ","-").split("-");
            if (StartTime[2].equals(date_day)){
                scheduleListDay.add(scheduleList.get(i));
            }
        }
        adapter.updataList(scheduleListDay);
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
        StatusBarUtil.setStatusBarColor(this, R.color.schedule_status_bar_bg);

    }

    //点击返回或者切换Fragment是关闭pop
    public void isShowPop(){
        if(mCalendar == null){
            mCalendar = getPopCalendar();
            mCalendar.show();
            popheight = mCalendar.getContentView().getMeasuredHeight();
        }else{
            if (!mCalendar.isShowing()) {
                mCalendar.show();
                popheight = mCalendar.getContentView().getMeasuredHeight();
            } else {
                if (mCalendar != null && mCalendar.isShowing()) {
                    mCalendar.dismiss();
                    //mCalendar.destroy();
                }
                popheight = 1;
            }
        }

        if(null != schedule_rili){
            schedule_rili.setLayoutParams(new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, popheight));
        }
    }

    public void closePop(){
        if (mCalendar != null && mCalendar.isShowing()) {
            mCalendar.dismiss();
            mCalendar.destroy();
        }
        popheight = 1;
        // 导航啦按钮
        if(null != schedule_rili) {
            schedule_rili
                    .setLayoutParams(new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.MATCH_PARENT, popheight));
        }
    }

    //退出Acivity之前先关闭popwindow
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            closePop();
        }
        return super.onKeyDown(keyCode, event);
    }

    enum SildeDirection {
        RIGHT, LEFT, NO_SILDE
    }

    class PopCalendar extends PopupWindow {

        private  int GRAVITY_FOR_POP = Gravity.BOTTOM;
        private  int X_LOCATION = 0;
        private  int Y_LOCATION = 0;
        public  PopCalendar instance;
        private ViewPager mViewPager;
        private CalendarViewAdapter<CalendarCard> popAdapter;
        private  TextView preImgBtn;
        private  TextView nextImgBtn;
        private  TextView slide_time;
        private  int mCurrentIndex = 498;
        private  SildeDirection mDirection = SildeDirection.NO_SILDE;
        private  CalendarCard[] views;

        public  List<Date> liang = new ArrayList<Date>();
        private Context context;
        private  View parent;


        public PopCalendar(Context context) {
            super(context);
            this.context = context;
        }

        public PopCalendar(View view, int matchParent, int wrapContent, View parent) {
            super(view, matchParent, wrapContent);
            this.parent = parent;
        }


        public  synchronized PopCalendar getInstance(Context context, View parent, int gravity,
                                                     CalendarCard.OnCellClickListener onClickdate, List<String> haveScheduleList) {
            if (gravity != -1) {
                GRAVITY_FOR_POP = gravity;
            }
            if (context == null) {
                return null;
            }
            if (parent == null) {
                return null;
            }

            if (null == instance) {
                final View view = LayoutInflater.from(context).inflate(R.layout.layout_calendar, null);
                // 强制绘制view的宽高
                view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                mViewPager = (ViewPager) view.findViewById(R.id.activity_user_calendar_Viewpager);
                preImgBtn = (TextView) view.findViewById(R.id.activity_user_calendar_PreMonthBtn);
                nextImgBtn = (TextView) view.findViewById(R.id.activity_user_calendar_NextMonthBtn);
                slide_time = (TextView) view.findViewById(R.id.slide_time);

                instance = new PopCalendar(view, WindowManager.LayoutParams.MATCH_PARENT,
                        WindowManager.LayoutParams.WRAP_CONTENT, parent);
                final CalendarCard.OnCellClickListener listener = onClickdate;

                slide_time.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        //设置ViewPaper当前的item
                        String year_month = setDate.getYear()+"-"+String.format("%02d",setDate.getMonth());
                        callService(year_month,0,null,false,"3");
                    }
                });

                preImgBtn.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        //设置ViewPaper当前的item
                        mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
                    }
                });
                nextImgBtn.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
                    }
                });
                class CellClickListener implements CalendarCard.OnCellClickListener {

                    @Override
                    public void clickDate(CustomDate date) {
                        if (listener != null) {
                            listener.clickDate(date);
                        }
                        // window.dismiss();
                    }

                    @Override
                    public void changeDate(CustomDate date) {
                        setDate = date;
                        if (listener != null) {
                            listener.changeDate(date);
                        }
                        slide_time.setText(date.getYear() + "年" + date.getMonth() + "月");
                        if (date.getMonth() == 1) {
                            preImgBtn.setText((date.getYear() - 1) + "年" + 12 + "月");
                        } else {
                            preImgBtn.setText(date.getYear() + "年" + (date.getMonth() - 1) + "月");
                        }
                        if (date.getMonth() == 12) {
                            nextImgBtn.setText(date.getYear() + 1 + "年" + 1 + "月");
                        } else {
                            nextImgBtn.setText(date.getYear() + "年" + (date.getMonth() + 1) + "月");
                        }
                    }
                }

                views = new CalendarCard[3];
                for (int i = 0; i < 3; i++) {
                    views[i] = new CalendarCard(context, new CellClickListener(), liang,haveScheduleList);
                }
                popAdapter = new CalendarViewAdapter<CalendarCard>(views);
                calendarCard = popAdapter.getAllItems()[0];
                setViewPager();

                ColorDrawable dw = new ColorDrawable(0xffffffff);// 更整个日历背景颜色
                instance.setBackgroundDrawable(dw);

            }
            return instance;
        }

        public void show() {
            if (null == instance){
                instance = ScheduleActivity.this.mCalendar;
            }
            instance.showAsDropDown(parent, X_LOCATION, Y_LOCATION);
        }
        private  void setViewPager() {
            mViewPager.setAdapter(popAdapter);
            mViewPager.setCurrentItem(498);
            mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

                @Override
                public void onPageSelected(int position) {

                    clickDateShare = null;//左右滑动时将点击日期置空
                    measureDirection(position);
                    updateCalendarView(position);
                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                }
            });
        }

        private  void measureDirection(int position) {

            if (position > mCurrentIndex) {
                mDirection = SildeDirection.RIGHT;
            } else if (position < mCurrentIndex) {
                mDirection = SildeDirection.LEFT;
            }
            mCurrentIndex = position;
        }

        private  void updateCalendarView(int position) {

            if (mDirection == SildeDirection.RIGHT) {
                ScheduleActivity.this.callService(rightDate(setDate),position,popAdapter, true,"1");
            } else if (mDirection == SildeDirection.LEFT) {
                ScheduleActivity.this.callService(leftDate(setDate),position,popAdapter,false,"1");
            }
        }

        public String leftDate(CustomDate setDate){
            String setMonth = null;
            if (setDate.getMonth()==1){
                dateString = ((setDate.getYear()-1)+"")+"-"+("12");
            }else{
                setMonth = String.format("%02d",setDate.getMonth()-1);
                dateString = ((setDate.getYear())+"")+"-"+setMonth;
            }
            //Toast.makeText(ScheduleActivity.this,dateString,Toast.LENGTH_LONG).show();
            return dateString;
        }
        public String rightDate(CustomDate setDate){
            String setMonth = null;
            if (setDate.getMonth()==12){
                dateString = ((setDate.getYear()+1)+"")+"-"+("01");
            }else{
                setMonth = String.format("%02d",setDate.getMonth()+1);

                dateString = ((setDate.getYear())+"")+"-"+setMonth;
            }

            return dateString;
        }
        public void destroy() {
            instance = null;
        }
    }

    public void slide(CalendarViewAdapter<CalendarCard> popAdapter, boolean isRight , int position){
        CalendarCard[] mShowViews = popAdapter.getAllItems();
        if (isRight){
            calendarCard = mShowViews[position % mShowViews.length];
            calendarCard.rightSlide(haveScheduleList);
        }else {
            calendarCard = mShowViews[position % mShowViews.length];
            calendarCard.leftSlide(haveScheduleList);
        }
    }
}

